package 代码随想录.回溯.a;

import java.util.ArrayList;
import java.util.List;

public class a216组合总和3 {
    public static List<List<Integer>> res;
    public static List<Integer> cur;


    static class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            res = new ArrayList<>();
            cur = new ArrayList<>();
            int index = 1;
            int sum = 0;
            backtracking(n, k, index, sum);
            return res;
        }

        public void backtracking(int n, int k, int index, int sum) {
            if (sum > n) {
                return;
            }
            if (cur.size() == k) {
                if (sum == n) {
                    res.add(new ArrayList<>(cur));
                }
                return;
            }
            for (int i = index; cur.size() + 9 - i + 1 >= k; i++) {
                cur.add(i);
                backtracking(n, k, i + 1, sum + i);
                cur.remove(cur.size() - 1);
            }
        }

    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int k = 3, n = 7;
        List<List<Integer>> lists = solution.combinationSum3(k, n);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
